package com.xywl.escort.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.support.v7.widget.AppCompatEditText;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import com.xywl.escort.R;
import java.lang.reflect.Field;

public class MNPasswordEditText extends AppCompatEditText {

    private static final String TAG = "MNPasswordEditText";

    private Context mContext;
    //长度
    private int maxLength;
    //文字大小
    private float textSize;
    //文字的画笔
    private Paint mPaintText;
    //线的画笔
    private Paint mPaintLine;
    //背景色
    private int backgroundColor;
    private int borderColor;
    private int textColor;
    private float borderRadius;
    private float borderWidth;
    private float itemMargin;
    private int coverCircleColor;
    private float coverCircleRadius;

    public MNPasswordEditText(Context context) {
        this(context, null);
    }

    public MNPasswordEditText(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MNPasswordEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;

        //初始化参数
        initAttrs(attrs, defStyleAttr);

        //初始化相关
        init();
    }

    private void initAttrs(AttributeSet attrs, int defStyleAttr) {
        TypedArray array = mContext.obtainStyledAttributes(attrs, R.styleable.MNPasswordEditText, defStyleAttr, 0);

        //背景色
        backgroundColor = array.getColor(R.styleable.MNPasswordEditText_mnPsw_background_color, Color.parseColor("#FFFFFF"));
        //边框颜色
        borderColor = array.getColor(R.styleable.MNPasswordEditText_mnPsw_border_color, Color.parseColor("#FF0000"));
        //文字的颜色
        textColor = array.getColor(R.styleable.MNPasswordEditText_mnPsw_text_color, Color.parseColor("#FF0000"));
        //边框圆角
        borderRadius = array.getDimension(R.styleable.MNPasswordEditText_mnPsw_border_radius, dip2px(6));
        //边框线大小
        borderWidth = array.getDimension(R.styleable.MNPasswordEditText_mnPsw_border_width, dip2px(1));
        //每个密码框的间隔
        itemMargin = array.getDimension(R.styleable.MNPasswordEditText_mnPsw_item_margin, dip2px(10));
        //圆形的颜色
        coverCircleColor = array.getColor(R.styleable.MNPasswordEditText_mnPsw_cover_circle_color, Color.parseColor("#FF0000"));
        //密码圆形遮盖半径
        coverCircleRadius = array.getDimension(R.styleable.MNPasswordEditText_mnPsw_cover_circle_radius, 0);
        //回收
        array.recycle();
    }

    private void init() {
        //最大的长度
        maxLength = getMaxLength();

        //文字的大小
        textSize = getTextSize();

        //初始化画笔
        //文字
        mPaintText = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaintText.setStyle(Paint.Style.FILL);
        mPaintText.setColor(textColor);
        mPaintText.setTextSize(textSize);

        //线
        mPaintLine = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaintLine.setStyle(Paint.Style.STROKE);
        mPaintLine.setColor(borderColor);
        mPaintLine.setStrokeWidth(borderWidth);

        //隐藏光标
        setCursorVisible(false);
        //设置本来文字的颜色为透明
        setTextColor(Color.TRANSPARENT);
        //触摸获取焦点
        setFocusableInTouchMode(true);
        //屏蔽长按
        setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                return true;
            }
        });
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //获取宽高
        int measuredWidth = getMeasuredWidth();
        float itemH = getMeasuredHeight();

        float margin = itemMargin;
        float itemW = measuredWidth / maxLength - margin;
        GradientDrawable drawable = new GradientDrawable();
        drawable.setStroke((int) borderWidth, borderColor);
        drawable.setCornerRadius(borderRadius);
        drawable.setColor(backgroundColor);
        Bitmap bitmap = drawableToBitmap(drawable, (int) itemW, (int) itemH);
        //画每个Item背景
        for (int i = 0; i < maxLength; i++) {
            float left = itemW * i + margin / 2 + margin * i;
            float top = 0;
            canvas.drawBitmap(bitmap, left, top, mPaintLine);
        }

        //写文字
        String currentText = getText().toString();
        for (int i = 0; i < maxLength; i++) {
            if (!TextUtils.isEmpty(currentText) && i < currentText.length()) {
                //圆形密码框输入
                //圆点半径
                float circleRadius = measuredWidth / maxLength * 0.5f * 0.3f;
                if (coverCircleRadius > 0) {
                    circleRadius = coverCircleRadius;
                }
                float startX = (measuredWidth / maxLength) / 2.0f + measuredWidth / maxLength * i;
                float startY = (itemH) / 2.0f;
                mPaintText.setColor(coverCircleColor);
                canvas.drawCircle(startX, startY, circleRadius, mPaintText);
            }
        }
    }

    public static Bitmap drawableToBitmap(Drawable drawable, int width, int height) {
        Bitmap bitmap = Bitmap.createBitmap(
                width,
                height,
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
        //刷新界面
        invalidate();
        if (mOnPasswordChangeListener != null) {
            mOnPasswordChangeListener.onPasswordChange(getText().toString());
        }
    }

    public int getMaxLength() {
        int length = 0;
        try {
            InputFilter[] inputFilters = getFilters();
            for (InputFilter filter : inputFilters) {
                Class<?> c = filter.getClass();
                if (c.getName().equals("android.text.InputFilter$LengthFilter")) {
                    Field[] f = c.getDeclaredFields();
                    for (Field field : f) {
                        if (field.getName().equals("mMax")) {
                            field.setAccessible(true);
                            length = (Integer) field.get(filter);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return length;
    }

    private int dip2px(float dpValue) {
        final float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private OnPasswordChangeListener mOnPasswordChangeListener;

    public void setOnPasswordChangeListener(OnPasswordChangeListener onPasswordChangeListener) {
        mOnPasswordChangeListener = onPasswordChangeListener;
    }

    public interface OnPasswordChangeListener {
        void onPasswordChange(String password);
    }

}